<script setup>
import { ref, watch } from 'vue';
import { message } from 'ant-design-vue';
import { UploadOutlined } from '@ant-design/icons-vue';
import { uploadFile } from "@/apis/uploadFile"
const props = defineProps({
    maxNum: {
        type: Number,
        required: true,
        default: 4,
    },
    list: {
        type: Array,
        required: true,
        default: 4,
    }
});
const emit = defineEmits(['upload','delete'])
const fileList = ref([])
watch(() => props.list, (newdata, old) => {
    fileList.value = [];
    if (props.list.length === 0) return;
    props.list.forEach((item, index) => {
        fileList.value.push({
            uid: index + 1,
            name: item.name,
            url: item.url,
        })
    })
}, { immediate: true, deep: true })
const beforeUpload = (file) => {
    uploadFile({ file: file }).then(res => {
        console.log(res);
        if (res.code === 1) {
            emit('upload', {
                name: res.data.file_name,
                url: res.data.url
            })
        } else {
            message.error(res.msg);
        }
    })
    return false;
}
const handleDeleteFile = (file) => {
    let arr = [];
    fileList.value.forEach((item, index) => {
        console.log(item.uid,file.uid);
        if (item.uid !== file.uid) {
            arr.push({
                name: item.name,
                url: item.url,
            })
        }
    })
    console.log(arr);
    emit("delete",arr)

}
</script>
<template>
    <a-upload :file-list="fileList" :before-upload="beforeUpload" name="file" @remove="handleDeleteFile">
        <a-button v-if="fileList.length < maxNum">
            <upload-outlined></upload-outlined>
            上传文件
        </a-button>
    </a-upload>
</template>
<style lang='scss' scoped></style>